package com.yunyao.framework.service.impl;

import com.alibaba.fastjson2.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.RedisKeyConstant;
import com.yunyao.common.constant.enums.ContractPriceType;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.constant.enums.DateFormatPattern;
import com.yunyao.common.constant.enums.ProjectSettlementStatusEnum;
import com.yunyao.common.constant.enums.ReconciliationStatusEnum;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.core.UserInfoRequest;
import com.yunyao.common.dto.excel.SettlementExcelDto;
import com.yunyao.common.dto.project.HistoryQtDto;
import com.yunyao.common.dto.project.ProjectSettlementDto;
import com.yunyao.common.dto.project.ProjectSettlementMaterialDto;
import com.yunyao.common.dto.project.ProjectSettlementOrderDto;
import com.yunyao.common.exception.BusinessException;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.model.*;
import com.yunyao.dao.service.bamu.*;
import com.yunyao.framework.audit.ProjectSettlementAuditHandle;
import com.yunyao.framework.dto.project.*;
import com.yunyao.framework.dto.reconciliation.ReconciliationMaterialDto;
import com.yunyao.framework.dto.supplier.SupplierSettlementPayNodeSaveDto;
import com.yunyao.framework.service.ProjectSettlementPayNodeService;
import com.yunyao.framework.service.ProjectSettlementService;
import com.yunyao.framework.service.ReconciliationService;
import com.yunyao.framework.service.SupplierSettlementPayNodeService;
import com.yunyao.framework.vo.project.ProjectSettlementInfoVO;
import com.yunyao.framework.vo.project.ProjectSettlementMaterialVO;
import com.yunyao.framework.vo.project.ProjectSettlementOrderVO;
import com.yunyao.framework.vo.project.ProjectSettlementVO;
import com.yunyao.framework.vo.reconciliation.ReconciliationMaterialVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xingjishuai
 * @date 2024-07-22
 */
@Slf4j
@Service
public class ProjectSettlementServiceImpl implements ProjectSettlementService {
    @Autowired
    private ProjectSettlementPayNodeService iBamuSupplierSettlementPayNodeService;
    @Autowired
    private IBamuReconciliationSettlementPayNodeService iBamuReconciliationSettlementPayNodeService;
    @Autowired
    private IBamuSaleContractService iBamuSaleContractService;
    @Autowired
    private ProjectSettlementAuditHandle projectSettlementAuditHandle;
    @Autowired
    private IBamuReconciliationOrderMaterialService iBamuReconciliationOrderMaterialService;
    @Autowired
    private IBamuReconciliationService iBamuReconciliationService;
    @Autowired
    private IBamuAuditConfirmHistoryService iBamuAuditConfirmHistoryService;
    @Autowired
    private IBamuContractWirePayService iBamuContractWirePayService;
    @Autowired
    private IBamuReconciliationSettlementOrderService iBamuReconciliationSettlementOrderService;
    @Autowired
    private IBamuReconciliationSettlementOrderMaterialService iBamuReconciliationSettlementOrderMaterialService;
    @Autowired
    private IBamuReconciliationSettlementService iBamuReconciliationSettlementService;
    @Resource
    private IBamuReconciliationSettlementPayNodeService settlementPayNodeService;
    @Resource
    private ReconciliationService reconciliationService;

    @Override
    public YResult<PageResult<ProjectSettlementVO>> pageList(ProjectSettlementDto projectSettlementDto) {
        // 构建查询条件
        LambdaQueryWrapper<BamuReconciliationSettlement> queryWrapper =
                new LambdaQueryWrapper<BamuReconciliationSettlement>()
                        .eq(BamuReconciliationSettlement::getIsDeleted, DataDeletedStatus.NO.getType())
                        .eq(StringUtils.isNotBlank(projectSettlementDto.getContractMethod()),
                                BamuReconciliationSettlement::getContractMethod,
                                projectSettlementDto.getContractMethod())
                        .eq(StringUtils.isNotBlank(projectSettlementDto.getContractId()), BamuReconciliationSettlement::getContractId, projectSettlementDto.getContractId())
                        .eq(StringUtils.isNotBlank(projectSettlementDto.getProjectId()),
                                BamuReconciliationSettlement::getProjectId,
                                projectSettlementDto.getProjectId())
                        .between(StringUtils.isNotBlank(projectSettlementDto.getSettlementStartDate()) && StringUtils.isNotBlank(projectSettlementDto.getSettlementEndDate()),
                                BamuReconciliationSettlement::getSettlementDate,
                                ConvertUtil.getStartOfDay(ConvertUtil.getString2Date(projectSettlementDto.getSettlementStartDate())),
                                ConvertUtil.getEndOfDay(ConvertUtil.getString2Date(projectSettlementDto.getSettlementEndDate())))
                        .like(StringUtils.isNotBlank(projectSettlementDto.getContractNo()),
                                BamuReconciliationSettlement::getContractNo,
                                projectSettlementDto.getContractNo())
                        .like(StringUtils.isNotBlank(projectSettlementDto.getContractName()), BamuReconciliationSettlement::getContractName, projectSettlementDto.getContractName())
                        .like(StringUtils.isNotBlank(projectSettlementDto.getProjectName()), BamuReconciliationSettlement::getProjectName, projectSettlementDto.getProjectName())
                        .like(StringUtils.isNotBlank(projectSettlementDto.getSupplierDeptName()), BamuReconciliationSettlement::getSupplierDeptName, projectSettlementDto.getSupplierDeptName())
                        .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuReconciliationSettlement::getProjectId, BaseContext.getProjectList())
                        .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()),
                                BamuReconciliationSettlement::getSupplierDeptId,
                                BaseContext.getSupplierList()).orderByDesc(BamuReconciliationSettlement::getId)
                        .orderByDesc(BamuReconciliationSettlement::getCreatedAt);

        // 分页查询
        IPage<BamuReconciliationSettlement> settlementPage = new Page<>(projectSettlementDto.getPageIndex(), projectSettlementDto.getPageSize());
        settlementPage = iBamuReconciliationSettlementService.page(settlementPage, queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<ProjectSettlementVO> voList = daoToVoList(settlementPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, settlementPage.getCurrent(), settlementPage.getSize(), settlementPage.getPages(), settlementPage.getTotal()));
    }

    @Override
    public YResult<PageResult<ProjectSettlementMaterialVO>> materialPageList(ProjectSettlementMaterialDto projectSettlementMaterialDto) {
        LambdaQueryWrapper<BamuReconciliationSettlementOrderMaterial> queryWrapper = new LambdaQueryWrapper<BamuReconciliationSettlementOrderMaterial>()
                .eq(BamuReconciliationSettlementOrderMaterial::getIsDeleted, DataDeletedStatus.NO.getType())
                .eq(BamuReconciliationSettlementOrderMaterial::getReconciliationSettlementId, projectSettlementMaterialDto.getReconciliationSettlementId())

                .orderByAsc(BamuReconciliationSettlementOrderMaterial::getMaterialSortNum);
        // 分页查询
        IPage<BamuReconciliationSettlementOrderMaterial> settlementPage = new Page<>(projectSettlementMaterialDto.getPageIndex(), projectSettlementMaterialDto.getPageSize());
        settlementPage = iBamuReconciliationSettlementOrderMaterialService.page(settlementPage, queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<ProjectSettlementMaterialVO> voList = materialDaoToVoList(settlementPage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(voList, settlementPage.getCurrent(), settlementPage.getSize(), settlementPage.getPages(), settlementPage.getTotal()));
    }


    @Override
    public YResult<PageResult<ReconciliationMaterialVO>> getReconciliationMaterialListbySupplyId(ReconciliationMaterialDto reconciliationMaterialDto) {
        LambdaQueryWrapper<BamuReconciliationOrderMaterial> wrapper = new LambdaQueryWrapper<BamuReconciliationOrderMaterial>()
                .in(BamuReconciliationOrderMaterial::getReconciliationId, reconciliationMaterialDto.getIdList()) // 使用in方法查询ID列表中的任意一个
//                .eq(BamuSoSupplyMaterial::getPurchaseApplyId, purchaseApplyId)
                .eq(BamuReconciliationOrderMaterial::getIsDeleted, DataDeletedStatus.NO.getType());

        // 分页查询
        IPage<BamuReconciliationOrderMaterial> payPage = new Page<>(reconciliationMaterialDto.getPageIndex(), reconciliationMaterialDto.getPageSize());
        payPage = iBamuReconciliationOrderMaterialService.page(payPage, wrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(payPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }


        // 转换为VO对象列表
        List<ReconciliationMaterialVO> materialVOList = materialDaoToVoList1(payPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(materialVOList, payPage.getCurrent(), payPage.getSize(), payPage.getPages(), payPage.getTotal()));

    }

    private List<ReconciliationMaterialVO> materialDaoToVoList1(List<BamuReconciliationOrderMaterial> records) {
        return records.stream().map(this::materialDaoToVo1).collect(Collectors.toList());
    }

    private ReconciliationMaterialVO materialDaoToVo1(BamuReconciliationOrderMaterial bamuReconciliationOrderMaterial) {
        ReconciliationMaterialVO reconciliationMaterialVO = new ReconciliationMaterialVO();
        BeanUtils.copyProperties(bamuReconciliationOrderMaterial, reconciliationMaterialVO);
        return reconciliationMaterialVO;
    }

    private List<ProjectSettlementMaterialVO> materialDaoToVoList(List<BamuReconciliationSettlementOrderMaterial> records) {
        return records.stream().map(this::materialDaoToVo).collect(Collectors.toList());
    }

    private ProjectSettlementMaterialVO materialDaoToVo(BamuReconciliationSettlementOrderMaterial bamuReconciliationSettlementOrderMaterial) {
        ProjectSettlementMaterialVO vo = new ProjectSettlementMaterialVO();
        BeanUtils.copyProperties(bamuReconciliationSettlementOrderMaterial, vo);
        return vo;
    }

    /**
     * 根据结算单ID获取项目结算信息
     * <p>
     * 此方法通过接收一个包含项目结算ID的参数对象，查询并返回相应的项目结算详细信息
     * 它首先尝试根据提供的ID从数据库中加载结算单如果找不到对应的结算单，或者结算单已被删除，
     * 则返回一个表示没有数据的错误结果否则，将数据库中的结算单信息转换为一个特定的值对象并返回
     *
     * @param settlementDto 包含项目结算ID的参数对象，用于指定需要查询的结算单
     * @return 返回一个包含项目结算详细信息的结果对象，或者在找不到数据时返回错误信息
     */
    @Override
    public YResult<ProjectSettlementInfoVO> getInfo(ProjectSettlementDto settlementDto) {
        // 提取传入参数中的结算单ID
        String id = settlementDto.getId();

        // 通过ID查询对应的结算单，同时确保查询到的结算单未被删除
        BamuReconciliationSettlement bamuReconciliationSettlement =
                iBamuReconciliationSettlementService.getByIdAndDeleted(id);

        // 如果查询不到对应的结算单或结算单已被删除，则返回一个表示没有数据的错误结果
        if (Objects.isNull(bamuReconciliationSettlement)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        // 如果查询成功，则将结算单信息转换为特定的值对象，并返回一个包含该信息的成功结果
        return YResult.success(daoToInfoVo(bamuReconciliationSettlement));
    }

    @Override
    /**
     * 确认项目结算
     *
     * @param projectSettlementConfirmDto 包含确认结算所需信息的数据传输对象
     * @return YResult<String> 包含操作结果和可能的错误信息
     */
    public YResult<String> confirm(ProjectSettlementConfirmDto projectSettlementConfirmDto) {
        // 提取DTO中的ID和其他确认信息
        String id = projectSettlementConfirmDto.getId();
        String confirmReconciliationFile =
                projectSettlementConfirmDto.getConfirmReconciliationFile();
        String confirmReconciliationMark =
                projectSettlementConfirmDto.getConfirmReconciliationMark();
        boolean isConfirmReconciliation = projectSettlementConfirmDto.getIsConfirmReconciliation();

        //要求附件必传
        if (StringUtils.isBlank(confirmReconciliationFile)) {
            return YResult.error(ResultMsgEnum.IMPORT_FILE_ISNULL);
        }
        // 根据ID获取结算信息，确保未被删除
        BamuReconciliationSettlement reconciliationSettlement =
                iBamuReconciliationSettlementService.getByIdAndDeleted(id);
        if (Objects.isNull(reconciliationSettlement)) {
            // 若找不到结算信息，返回错误结果
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算状态是否为供应商已确认
        Integer status = reconciliationSettlement.getStatus();
        if (status != ProjectSettlementStatusEnum.CONFIRMED_BY_SUPPLIER.getType()) {
            // 若状态不正确，返回错误结果
            return YResult.error(ResultMsgEnum.RECONCILIATION_SETTLEMENT_STAY_CONFIRMED);
        }
        int reconciliationSettlementStatus = isConfirmReconciliation ?
                ProjectSettlementStatusEnum.CONFIRMED_BY_CLOUD_ACQUISITION.getType() :
                ProjectSettlementStatusEnum.SUPPLIER_CONFIRMATION_REJECTION.getType();
        // 更新结算状态为云采购已确认，并保存确认凭证和标记
        reconciliationSettlement.setStatus(reconciliationSettlementStatus);
        reconciliationSettlement.setConfirmReconciliationFile(confirmReconciliationFile);
        reconciliationSettlement.setConfirmReconciliationMark(confirmReconciliationMark);
        iBamuReconciliationSettlementService.updateById(reconciliationSettlement);

        // 记录审核确认历史
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        iBamuAuditConfirmHistoryService.insertRecord(reconciliationSettlement.getId(), new Date()
                , reconciliationSettlement.getReconciliationPrice(),
                confirmReconciliationFile,
                confirmReconciliationMark, reconciliationSettlementStatus, "1",
                userInfo.getRealName());

        // 返回操作成功的结果
        return YResult.success(reconciliationSettlement.getId());
    }

    @Override
    public YResult<PageResult<ProjectSettlementOrderVO>> orderPageList(ProjectSettlementOrderDto projectSettlementOrderDto) {
        LambdaQueryWrapper<BamuReconciliationSettlementOrder> queryWrapper =
                new LambdaQueryWrapper<BamuReconciliationSettlementOrder>().eq(BamuReconciliationSettlementOrder::getIsDeleted, DataDeletedStatus.NO.getType()).eq(BamuReconciliationSettlementOrder::getReconciliationSettlementId, projectSettlementOrderDto.getReconciliationSettlementId()).orderByAsc(BamuReconciliationSettlementOrder::getId);
        // 分页查询
        IPage<BamuReconciliationSettlementOrder> settlementPage =
                new Page<>(projectSettlementOrderDto.getPageIndex(),
                        projectSettlementOrderDto.getPageSize());
        settlementPage = iBamuReconciliationSettlementOrderService.page(settlementPage,
                queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<ProjectSettlementOrderVO> voList = orderDaoToVoList(settlementPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, settlementPage.getCurrent(),
                settlementPage.getSize(), settlementPage.getPages(), settlementPage.getTotal()));
    }

    /**
     * 保存项目结算信息
     *
     * @param saveDto 项目结算保存DTO，包含需要保存或更新的项目结算信息
     * @return YResult<String> 返回一个包含操作结果的消息对象，其中包含结算ID
     */
    @Override
    public YResult<String> save(ProjectSettlementSaveDto saveDto) {
        checkSaveData(saveDto);
        // 初始化一个新的结算实体类，用于存储结算信息
        BamuReconciliationSettlement settlement = new BamuReconciliationSettlement();
        settlement.setId(saveDto.getId());
        String contractId = saveDto.getContractId();
        saveSaleContractInfo(contractId, settlement);
        settlement.setStatus(0);
        settlement.setContractMethod(saveDto.getContractMethod());
        // 设置对账开始日期，将字符串转换为日期类型
        settlement.setReconciliationStartDate(DateUtils.parseDate(saveDto.getReconciliationStartDate(), DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
        // 设置对账结束日期，同样将字符串转换为日期类型
        settlement.setReconciliationEndDate(DateUtils.parseDate(saveDto.getReconciliationEndDate(),
                DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
        // 设置结算日期，将字符串转换为日期类型
        settlement.setSettlementDate(DateUtils.parseDate(saveDto.getSettlementDate(), DateFormatPattern.YEAR_MONTH_DAY.getPattern()));

        //BamuPurchaseApply apply = purchaseApplyService.getOderId(saveDto.getOrderNo(), saveDto.getContractId());
        settlement.setOrderNo(saveDto.getOrderNo());
        settlement.setOrderId(saveDto.getOrderId());

        if (saveDto.getId() == null) {
            HistoryQtDto dto = new HistoryQtDto();
            dto.setContractId(saveDto.getContractId());
            BigDecimal historyPrice = getSupplyTaxTotalPrice(dto);
            settlement.setHistorySettlementAmount(historyPrice);
        } else {
            settlement.setHistorySettlementAmount(saveDto.getHistorySettlementAmount());
        }
        // 调用服务层方法保存或更新结算信息
        iBamuReconciliationSettlementService.saveOrUpdate(settlement);

        reconciliationSettlementOrderBatch(saveDto.getReconciliationIdList(),
                settlement.getId());
        updateSupplyInfo(settlement.getId());

        ProjectSettlementPayNodeSaveDto supplierSettlementPayNodeSaveDto = new ProjectSettlementPayNodeSaveDto();
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        if (CollectionUtils.isNotEmpty(saveDto.getPayNodeIdList())) {
            for (ProjectSettlementPayNodeSaveDto payNode : saveDto.getPayNodeIdList()) {
                supplierSettlementPayNodeSaveDto.setPaymentNode(payNode.getPaymentNode());
                Integer paidRatio = Integer.valueOf(payNode.getPaidRatio().replace("%", ""));
                Integer thispaidRatio = Integer.valueOf(payNode.getThisPaidRatio().replace("%", ""));
                Integer paymentRatio = paidRatio + thispaidRatio;
                supplierSettlementPayNodeSaveDto.setId(payNode.getId());
                supplierSettlementPayNodeSaveDto.setThisPaidRatio(thispaidRatio + "%");
                supplierSettlementPayNodeSaveDto.setPaidRatio(payNode.getPaidRatio() + "%");
                supplierSettlementPayNodeSaveDto.setPaymentRatio(paymentRatio + "%");
                supplierSettlementPayNodeSaveDto.setSettlementId(settlement.getId());
                supplierSettlementPayNodeSaveDto.setContractId(settlement.getContractId());
                supplierSettlementPayNodeSaveDto.setCreatedAt(new Date());
                supplierSettlementPayNodeSaveDto.setCreatedBy(userInfo.getRealName());
                supplierSettlementPayNodeSaveDto.setContractMethod(settlement.getContractMethod());
//        supplierSettlementPayNodeSaveDto.setOrderId(settlement.getProjectId());
                supplierSettlementPayNodeSaveDto.setIsDeleted(0);
                iBamuSupplierSettlementPayNodeService.saveInfo(supplierSettlementPayNodeSaveDto);
            }
        }


        // 返回成功结果，携带结算ID
        return YResult.success(settlement.getId());
    }


    /**
     * 获取结算历史金额
     *
     * @param dto
     * @return
     */
    @Override
    public BigDecimal getSupplyTaxTotalPrice(HistoryQtDto dto) {
        List<BamuReconciliationSettlementOrder> list = iBamuReconciliationSettlementOrderService.lambdaQuery()
                .eq(BamuReconciliationSettlementOrder::getContractId, dto.getContractId())
                .eq(BamuReconciliationSettlementOrder::getIsDeleted, DataDeletedStatus.NO.getType())
                .eq(BamuReconciliationSettlementOrder::getStatus, ReconciliationStatusEnum.CLOUD_ACQUISITION_CONFIRMATION_COMPLETE)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return BigDecimal.ZERO;
        }
        return list
                .stream()
                .map(BamuReconciliationSettlementOrder::getReconciliationPrice)
                .reduce(BigDecimal::add)
                .orElse(BigDecimal.ZERO);


        /*return iBamuReconciliationSettlementService.lambdaQuery()
                .eq(BamuReconciliationSettlement::getContractId, dto.getContractId())
                .eq(BamuReconciliationSettlement::getIsDeleted, 0)
                .orderByDesc(BamuReconciliationSettlement::getCreatedAt)
                .last("limit 1")
                .oneOpt()
                .map(BamuReconciliationSettlement::getHistorySettlementAmount)
                .orElse(BigDecimal.ZERO);*/
    }


    private void saveSaleContractInfo(String contractId, BamuReconciliationSettlement settlement) {
        BamuSaleContract bamuSaleContract = iBamuSaleContractService.getByIdNoDelete(contractId);
        if (Objects.isNull(bamuSaleContract)) {
            return;
        }
        settlement.setContractId(contractId);
        settlement.setContractNo(bamuSaleContract.getContractNo());
        settlement.setContractName(bamuSaleContract.getContractName());
        settlement.setPurchaseDeptId(bamuSaleContract.getPurchaseDeptId());
        settlement.setPurchaseDeptName(bamuSaleContract.getPurchaseDeptName());
        settlement.setPurchaseDeptName(bamuSaleContract.getPurchaseDeptName());
        settlement.setProjectId(bamuSaleContract.getProjectId());
        settlement.setProjectName(bamuSaleContract.getProjectName());
        settlement.setSupplyDeptId(bamuSaleContract.getSupplyDeptId());
        settlement.setSupplyDeptName(bamuSaleContract.getSupplyDeptName());
        settlement.setSupplierDeptId(bamuSaleContract.getSupplierDeptId());
        settlement.setSupplierDeptName(bamuSaleContract.getSupplierDeptName());
        settlement.setContractMethod(bamuSaleContract.getContractMethod());
        settlement.setProjectDeptId(bamuSaleContract.getProjectDeptId());
        settlement.setProjectDeptName(bamuSaleContract.getProjectDeptName());
    }

    private void checkSaveData(ProjectSettlementSaveDto saveDto) {
        String contractId = saveDto.getContractId();
        if (StringUtils.isBlank(contractId)) {
            throw new BusinessException("合同参数必传");
        }
        BamuSaleContract bamuSaleContract = iBamuSaleContractService.getByIdNoDelete(contractId);
        if (Objects.isNull(bamuSaleContract)) {
            throw new BusinessException("未查询可用合同");
        }
        String settlementDate = saveDto.getSettlementDate();
        if (StringUtils.isBlank(settlementDate)) {
            throw new BusinessException("结算时间参数必传");
        }
        List<String> reconciliationIdList = saveDto.getReconciliationIdList();
        if (CollectionUtils.isEmpty(reconciliationIdList)) {
            throw new BusinessException("对账单参数必传");
        }
        List<String> distinctReconciliationIdList =
                reconciliationIdList.stream().distinct().toList();
        if (distinctReconciliationIdList.size() != reconciliationIdList.size()) {
            throw new BusinessException("对账单参数重复");
        }
    }

    private void reconciliationSettlementOrderBatch(List<String> reconciliationIdList,
                                                    String reconciliationSettlementId) {
        // 检查对账单ID列表是否为空
        if (CollectionUtils.isEmpty(reconciliationIdList)) {
            throw new BusinessException("对账单参数必传");
        }
        // 根据对账单ID列表查询已删除的对账单信息
        List<BamuReconciliation> bamuReconciliationList = iBamuReconciliationService.listByIdsDeleted(reconciliationIdList);
        if (CollectionUtils.isEmpty(bamuReconciliationList)) {
            throw new BusinessException("对账单信息异常");
        }
        List<BamuReconciliationSettlementOrder> reconciliationSettlementOrders =
                iBamuReconciliationSettlementOrderService.listByReconciliationSettlementIdDeleted(reconciliationSettlementId);
        List<String> oldReconciliationIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(reconciliationSettlementOrders)) {
            List<String> deleteIdList =
                    reconciliationSettlementOrders.stream().map(BamuReconciliationSettlementOrder::getReconciliationId)
                            .filter(reconciliationId -> !reconciliationIdList.contains(reconciliationId)).toList();
            if (CollectionUtils.isNotEmpty(deleteIdList)) {
                iBamuReconciliationSettlementOrderService.deletedByReconciliationIdList(deleteIdList);
                iBamuReconciliationSettlementOrderMaterialService.deletedByReconciliationIdList(deleteIdList);
                iBamuReconciliationService.unBindSettlement(deleteIdList);
            }
            oldReconciliationIdList =
                    reconciliationSettlementOrders.stream().map(BamuReconciliationSettlementOrder::getReconciliationId).toList();
        }
        List<String> finalOldReconciliationIdList = oldReconciliationIdList;
        List<String> filterReconciliationIdList = reconciliationIdList.stream().filter(x -> !finalOldReconciliationIdList.contains(x)).toList();
        if (CollectionUtils.isEmpty(filterReconciliationIdList)) {
            return;
        }
        List<BamuReconciliation> reconciliationList = bamuReconciliationList.stream().filter(x -> filterReconciliationIdList.contains(x.getId())).toList();
        // 批量保存对账单与结算单的关联关系
        reconciliationSettlementSaveBatch(reconciliationList, reconciliationSettlementId, filterReconciliationIdList);
    }

    private void updateSupplyInfo(String reconciliationSettlementId) {
        BamuReconciliationSettlement settlement = new BamuReconciliationSettlement();
        settlement.setId(reconciliationSettlementId);
        List<BamuReconciliationSettlementOrder> reconciliationSettlementOrders =
                iBamuReconciliationSettlementOrderService.listByReconciliationSettlementIdDeleted(reconciliationSettlementId);
        if (CollectionUtils.isEmpty(reconciliationSettlementOrders)) {
            return;
        }
        int supplyNum =
                reconciliationSettlementOrders.stream().map(BamuReconciliationSettlementOrder::getSupplyNum).mapToInt(Integer::intValue).sum();
        double supplyIncludingTaxTotalPrice =
                reconciliationSettlementOrders.stream().map(BamuReconciliationSettlementOrder::getSupplyIncludingTaxTotalPrice).mapToDouble(BigDecimal::doubleValue).sum();
        double reconciliationPrice =
                reconciliationSettlementOrders.stream().map(BamuReconciliationSettlementOrder::getReconciliationPrice).mapToDouble(BigDecimal::doubleValue).sum();
        settlement.setSupplyNum(supplyNum);
        settlement.setSupplyIncludingTaxTotalPrice(BigDecimal.valueOf(supplyIncludingTaxTotalPrice));
        settlement.setSettlementNum(reconciliationSettlementOrders.size());
        settlement.setReconciliationPrice(BigDecimal.valueOf(reconciliationPrice));
        iBamuReconciliationSettlementService.updateById(settlement);
    }

    private void reconciliationSettlementSaveBatch(List<BamuReconciliation> reconciliationList,
                                                   String reconciliationSettlementId, List<String> filterReconciliationIdList) {

        List<BamuReconciliationSettlementOrder> bamuReconciliationSettlementOrderList =
                reconciliationList.stream().map(x -> reconciliationToSettlementOrder(x, reconciliationSettlementId)).collect(Collectors.toList());
        iBamuReconciliationSettlementOrderService.saveBatch(bamuReconciliationSettlementOrderList);
        iBamuReconciliationService.bindSettlement(filterReconciliationIdList);
        // 遍历保存后的对账结算订单信息
        for (BamuReconciliationSettlementOrder bamuReconciliationSettlementOrder : bamuReconciliationSettlementOrderList) {
            // 获取当前对账结算订单的ID
            String id = bamuReconciliationSettlementOrder.getId();
            // 获取当前对账结算订单关联的对账单ID
            String reconciliationId = bamuReconciliationSettlementOrder.getReconciliationId();
            // 根据对账单ID查询对账订单材料信息
            List<BamuReconciliationOrderMaterial> reconciliationOrderMaterialList = iBamuReconciliationOrderMaterialService.listByReconciliationId(reconciliationId);
            // 如果对账订单材料信息列表不为空
            if (CollectionUtils.isNotEmpty(reconciliationOrderMaterialList)) {
                // 将对账订单材料信息转换为对账结算订单材料信息，并收集为列表
                List<BamuReconciliationSettlementOrderMaterial> bamuReconciliationOrderMaterialList =
                        reconciliationOrderMaterialList.stream().map(x -> reconciliationToSettlementOrderMaterial(x, reconciliationSettlementId, id)).toList();
                // 批量保存对账结算订单材料信息
                iBamuReconciliationSettlementOrderMaterialService.saveBatch(bamuReconciliationOrderMaterialList);
            }
        }
    }


    /**
     * 将对账单物料信息转换为结算单物料信息
     *
     * @param bamuReconciliationOrderMaterial 对账单物料信息，用于填充结算单物料信息的初始数据
     * @param reconciliationSettlementId      结算单ID，用于标识特定的结算单
     * @param reconciliationSettlementOrderId 结算单订单ID，用于在结算单中标识特定的订单
     * @return 返回转换后的结算单物料信息对象
     */
    private BamuReconciliationSettlementOrderMaterial reconciliationToSettlementOrderMaterial(BamuReconciliationOrderMaterial bamuReconciliationOrderMaterial,
                                                                                              String reconciliationSettlementId,
                                                                                              String reconciliationSettlementOrderId) {
        // 初始化结算单物料信息对象
        BamuReconciliationSettlementOrderMaterial bamuReconciliationSettlementOrderMaterial =
                new BamuReconciliationSettlementOrderMaterial();
        // 复制对账单物料信息到结算单物料信息中
        BeanUtils.copyProperties(bamuReconciliationOrderMaterial,
                bamuReconciliationSettlementOrderMaterial);
        // 设置结算单ID
        bamuReconciliationSettlementOrderMaterial.setReconciliationSettlementId(reconciliationSettlementId);
        // 设置结算单订单ID
        bamuReconciliationSettlementOrderMaterial.setReconciliationSettlementOrderId(reconciliationSettlementOrderId);
        // 重置ID为null，因为在新的结算单物料信息中，它将是一个新的记录，需要重新生成ID
        bamuReconciliationSettlementOrderMaterial.setId(null);
        // 返回转换后的结算单物料信息对象
        return bamuReconciliationSettlementOrderMaterial;
    }


    /**
     * 将对账结果转换为结算单
     * <p>
     * 此方法的主要目的是为了创建一个新的结算单对象，该对象基于现有的对账结果
     * 它使用BeanUtils的copyProperties方法来复制对账结果的属性到新的结算单对象中
     * 并设置了新的结算单ID，对账ID，并将新结算单对象的ID设置为null
     *
     * @param bamuReconciliation         对账结果对象，其属性将被复制到新的结算单对象中
     * @param reconciliationSettlementId 结算单的唯一标识符
     * @return 返回一个新的结算单对象，该对象是根据对账结果和结算单ID创建的
     */
    private BamuReconciliationSettlementOrder reconciliationToSettlementOrder(BamuReconciliation bamuReconciliation, String reconciliationSettlementId) {
        // 创建一个新的结算单对象，用于存储转换后的对账结果
        BamuReconciliationSettlementOrder bamuReconciliationSettlementOrder =
                new BamuReconciliationSettlementOrder();
        // 复制对账结果的属性到新的结算单对象中
        BeanUtils.copyProperties(bamuReconciliation, bamuReconciliationSettlementOrder);
        // 设置新的结算单ID
        bamuReconciliationSettlementOrder.setReconciliationSettlementId(reconciliationSettlementId);
        // 设置对账ID
        bamuReconciliationSettlementOrder.setReconciliationId(bamuReconciliation.getId());
        // 将新结算单对象的ID设置为null，以标识这是一个新的对象
        bamuReconciliationSettlementOrder.setId(null);
        // 返回转换后的结算单对象
        return bamuReconciliationSettlementOrder;
    }

    /**
     * 核对结算单据检查
     *
     * @param projectSettlementCheckDto 包含核对结算单据的ID、核对价格、核对文件和核对备注
     * @return YResult对象，包含成功或错误信息以及可能的核对结算单据ID
     */
    @Override
    public YResult<String> check(ProjectSettlementCheckDto projectSettlementCheckDto) {
        // 提取DTO中的主要字段
        String id = projectSettlementCheckDto.getId();
        BigDecimal reconciliationPrice = projectSettlementCheckDto.getReconciliationPrice();
        String checkFile = projectSettlementCheckDto.getCheckFile();
        String checkMark = projectSettlementCheckDto.getCheckMark();
        if (!ConvertUtil.isValidNotEmptyJson(checkFile)) {
            checkFile = "[]";
        }
        // 根据ID获取核对结算单据，确保它未被删除
        BamuReconciliationSettlement reconciliationSettlement =
                iBamuReconciliationSettlementService.getByIdAndDeleted(id);
        if (Objects.isNull(reconciliationSettlement)) {
            // 如果找不到结算单据，返回错误信息
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算单据的状态是否为“待核对”
        Integer status = reconciliationSettlement.getStatus();
        if (status != ProjectSettlementStatusEnum.TO_BE_CHECKED.getType()) {
            // 如果不在“待核对”状态，返回错误信息
            return YResult.error(ResultMsgEnum.RECONCILIATION_SETTLEMENT_CHECK);
        }

        // 更新核对结算单据的信息，包括核对价格、核对文件、核对备注，并将其状态更改为“已核对”
        //reconciliationSettlement.setReconciliationPrice(reconciliationPrice);
        reconciliationSettlement.setCheckFile(checkFile);
        reconciliationSettlement.setCheckMark(checkMark);
        reconciliationSettlement.setStatus(ProjectSettlementStatusEnum.CHECKED_OUT.getType());
        iBamuReconciliationSettlementService.updateById(reconciliationSettlement);

        // 记录核对操作的历史记录
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        iBamuAuditConfirmHistoryService.insertRecord(reconciliationSettlement.getId(), new Date()
                , reconciliationPrice, checkFile, checkMark,
                ProjectSettlementStatusEnum.CHECKED_OUT.getType(), "0",
                userInfo.getRealName());

        // 返回成功结果，包含核对结算单据的ID
        return YResult.success(reconciliationSettlement.getId());
    }

    @Override
    public YResult<String> submitApproval(ProjectSettlementSubmitApprovalDto submitApprovalDto) {
        try {
            // 调用处理类的submit方法，传入审批ID，执行审批提交操作
            projectSettlementAuditHandle.submit(submitApprovalDto.getId());
            // 如果审批提交成功，返回成功结果，包含审批的ID
            return YResult.success(submitApprovalDto.getId());
        } catch (Exception e) {
            log.error("提交审批异常", e);
            // 如果审批提交过程中发生异常，返回错误结果，包含异常信息
            return YResult.error(ResultMsgEnum.SUBMIT_APPROVAL_ERROR);
        }
    }

    @Override
    public YResult<String> approval(ProjectSettlementApprovalDto approvalDto) {
        try {
            // 调用项目结算审批处理类的approval方法进行审批操作
            projectSettlementAuditHandle.approval(approvalDto);
            // 审批成功后，返回成功结果，携带审批后的ID
            return YResult.success(approvalDto.getId());
        } catch (Exception e) {
            log.error("审批项目结算失败", e);
            // 审批过程中发生异常，返回错误结果，携带异常信息
            return YResult.error(ResultMsgEnum.APPROVAL_ERROR);
        }
    }

    @Override
    public YResult<String> deleted(ProjectSettlementDeletedDto projectSettlementDeletedDto) {
        try {
            String id = projectSettlementDeletedDto.getId();
            BamuReconciliationSettlement reconciliationSettlement =
                    iBamuReconciliationSettlementService.getByIdAndDeleted(id);
            if (Objects.isNull(reconciliationSettlement)) {
                // 如果找不到结算单据，返回错误信息
                return YResult.error(ResultMsgEnum.NO_DATA);
            }
            if (reconciliationSettlement.getIsDeleted() == DataDeletedStatus.YES.getType()) {
                // 如果结算单据已经被删除，返回错误信息
                return YResult.error(ResultMsgEnum.DELETED_DELETED_DATA_ERROR);
            }
            reconciliationSettlement.setIsDeleted(DataDeletedStatus.YES.getType());
            iBamuReconciliationSettlementService.updateById(reconciliationSettlement);
            return YResult.success(id);
        } catch (Exception e) {
            log.error("删除项目结算失败", e);
            // 如果删除失败，返回错误结果，携带异常信息
            return YResult.error(ResultMsgEnum.SYS_ERROR);
        }
    }

    @Override
    public YResult<String> ycConfirm(ProjectSettlementConfirmDto projectSettlementConfirmDto) {
        // 提取DTO中的ID和其他确认信息
        String id = projectSettlementConfirmDto.getId();
        String confirmReconciliationFile =
                projectSettlementConfirmDto.getConfirmReconciliationFile();
        String confirmReconciliationMark =
                projectSettlementConfirmDto.getConfirmReconciliationMark();


        // 根据ID获取结算信息，确保未被删除
        BamuReconciliationSettlement reconciliationSettlement =
                iBamuReconciliationSettlementService.getByIdAndDeleted(id);
        if (Objects.isNull(reconciliationSettlement)) {
            // 若找不到结算信息，返回错误结果
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算状态是否为供应商已确认
        Integer status = reconciliationSettlement.getStatus();
        if (status != ProjectSettlementStatusEnum.CONFIRMED_BY_CLOUD_ACQUISITION.getType()) {
            // 若状态不正确，返回错误结果
            return YResult.error(ResultMsgEnum.RECONCILIATION_SETTLEMENT_STAY_YC_CONFIRMED);
        }

        // 更新结算状态为云采购已确认，并保存确认凭证和标记
        reconciliationSettlement.setStatus(ProjectSettlementStatusEnum.PAYMENT_TO_BE_COLLECTED.getType());
        if (ConvertUtil.isValidNotEmptyJson(confirmReconciliationFile)) {
            reconciliationSettlement.setYcFile(confirmReconciliationFile);
        } else {
            reconciliationSettlement.setYcFile("[]");
        }

        reconciliationSettlement.setYcConfirmMark(confirmReconciliationMark);
        iBamuReconciliationSettlementService.updateById(reconciliationSettlement);
        updateReconciliationSuccessStatus(id);
        // 记录审核确认历史
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        iBamuAuditConfirmHistoryService.insertRecord(reconciliationSettlement.getId(), new Date()
                , reconciliationSettlement.getReconciliationPrice(), confirmReconciliationFile,
                confirmReconciliationMark,
                ProjectSettlementStatusEnum.PAYMENT_TO_BE_COLLECTED.getType(), "3",
                userInfo.getRealName());

        // 返回操作成功的结果
        return YResult.success(reconciliationSettlement.getId());
    }


    private void updateReconciliationSuccessStatus(String id) {
        List<BamuReconciliationSettlementOrder> reconciliationSettlementOrderList =
                iBamuReconciliationSettlementOrderService.listByReconciliationSettlementIdDeleted(id);
        if (CollectionUtils.isEmpty(reconciliationSettlementOrderList)) {
            return;
        }
        for (BamuReconciliationSettlementOrder bamuReconciliationSettlementOrder : reconciliationSettlementOrderList) {
            String reconciliationId = bamuReconciliationSettlementOrder.getReconciliationId();
            BamuReconciliation bamuReconciliation =
                    iBamuReconciliationService.getByIdNoDelete(reconciliationId);
            if (Objects.isNull(bamuReconciliation)) {
                return;
            }
            Integer status = bamuReconciliation.getStatus();
            if (Objects.equals(status, ReconciliationStatusEnum.PAYMENT_COLLECTION_IN_PROGRESS.getType())) {
                bamuReconciliation.setStatus(ReconciliationStatusEnum.PAYMENT_COLLECTION_COMPLETE.getType());
                iBamuReconciliationService.updateById(bamuReconciliation);
            }
        }
    }

    @Override
    public YResult<Map<String, Object>> materialCount(ProjectSettlementMaterialDto projectSettlementMaterialDto) {
        String reconciliationSettlementId =
                projectSettlementMaterialDto.getReconciliationSettlementId();
        Map<String, Object> map =
                iBamuReconciliationSettlementOrderMaterialService.getMaterialSumMap(reconciliationSettlementId);
        return YResult.success(map);
    }


    private List<ProjectSettlementOrderVO> orderDaoToVoList(List<BamuReconciliationSettlementOrder> records) {
        return records.stream().map(this::orderDaoToVo).collect(Collectors.toList());
    }

    private ProjectSettlementOrderVO orderDaoToVo(BamuReconciliationSettlementOrder bamuReconciliationSettlementOrder) {
        ProjectSettlementOrderVO projectSettlementOrderVO = new ProjectSettlementOrderVO();
        BeanUtils.copyProperties(bamuReconciliationSettlementOrder, projectSettlementOrderVO);
        return projectSettlementOrderVO;
    }

    private ProjectSettlementInfoVO daoToInfoVo(BamuReconciliationSettlement settlement) {
        ProjectSettlementInfoVO infoVO = new ProjectSettlementInfoVO();
        List<BamuReconciliationSettlementPayNode> payNodes = settlementPayNodeService.lambdaQuery()
                .eq(BamuReconciliationSettlementPayNode::getContractId, settlement.getContractId())
                .eq(BamuReconciliationSettlementPayNode::getOrderId, settlement.getOrderId())
                .eq(BamuReconciliationSettlementPayNode::getIsDeleted, 0)
                .list();
        infoVO.setReconciliationSettlementPayNodes(payNodes);
        BeanUtils.copyProperties(settlement, infoVO);

        //获取合同id
        String contractId = settlement.getContractId();
        //根据合同id，获取历史对账单
        List<BamuReconciliationSettlement> list = iBamuReconciliationSettlementService.lambdaQuery()
                .eq(BamuReconciliationSettlement::getContractId, contractId)
                .lt(BamuReconciliationSettlement::getCreatedAt,settlement.getCreatedAt())
                .eq(BamuReconciliationSettlement::getIsDeleted, DataDeletedStatus.NO.getType()).list();
        if(CollectionUtils.isNotEmpty(list)){
            List<String> idList = list.stream().map(BamuReconciliationSettlement::getId).distinct().toList();
            //查询材料表，获取所有结算单的历史结算金额
            List<BamuReconciliationSettlementOrderMaterial> resultList = iBamuReconciliationSettlementOrderMaterialService.lambdaQuery()
                    .in(BamuReconciliationSettlementOrderMaterial::getReconciliationSettlementId, idList)
                    .list();
            if(CollectionUtils.isNotEmpty(resultList)){
                BigDecimal sum = resultList.stream().map(BamuReconciliationSettlementOrderMaterial::getReconciliationPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                infoVO.setHistorySettlementAmount(sum);
            }
        }
        return infoVO;
    }

    private List<ProjectSettlementVO> daoToVoList(List<BamuReconciliationSettlement> records) {
        List<String> contractIdList = records.stream().map(BamuReconciliationSettlement::getContractId).distinct().toList();
        Map<String, BamuContractWirePay> contractWirePayMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(contractIdList)) {
            contractWirePayMap.putAll(iBamuContractWirePayService.mapByContractIdList(contractIdList));
        }
        return records.stream().map(x -> daoToVo(x, contractWirePayMap)).collect(Collectors.toList());
    }

    /**
     * 将数据库访问对象转换为视图对象
     * 此方法主要用于将结算信息从数据库对象转换为前端展示对象，如果存在对应的合同付款信息，也将其价格类型一并转换
     *
     * @param bamuReconciliationSettlement 结算信息数据库对象
     * @param contractWirePayMap           合同付款信息的映射表，用于查找合同对应的付款信息
     * @return 返回转换后的项目结算视图对象
     */
    private ProjectSettlementVO daoToVo(BamuReconciliationSettlement bamuReconciliationSettlement, Map<String, BamuContractWirePay> contractWirePayMap) {
        // 创建视图对象实例
        ProjectSettlementVO vo = new ProjectSettlementVO();
        // 复制数据库对象的基本属性到视图对象
        BeanUtils.copyProperties(bamuReconciliationSettlement, vo);
        // 根据合同ID从映射表中获取合同付款信息
        BamuContractWirePay contractWirePay = contractWirePayMap.get(bamuReconciliationSettlement.getContractId());
        // 检查合同付款信息是否非空
        if (Objects.nonNull(contractWirePay)) {
            // 如果非空，则将合同付款信息中的价格类型复制到视图对象
            vo.setPriceType(contractWirePay.getPriceType());
            vo.setPriceTypeDesc(ContractPriceType.typeOfDesc(Integer.valueOf(contractWirePay.getPriceType())));
            vo.setPaymentCycle(contractWirePay.getPaymentCycle());
        }
        //获取合同id
        String contractId = bamuReconciliationSettlement.getContractId();
        //根据合同id，获取历史对账单
        List<BamuReconciliationSettlement> list = iBamuReconciliationSettlementService.lambdaQuery()
                .eq(BamuReconciliationSettlement::getContractId, contractId)
                .eq(BamuReconciliationSettlement::getIsDeleted, DataDeletedStatus.NO.getType()).list();
        if(CollectionUtils.isNotEmpty(list)){
            List<String> idList = list.stream().map(BamuReconciliationSettlement::getId).distinct().toList();
            //查询材料表，获取所有结算单的历史结算金额
            List<BamuReconciliationSettlementOrderMaterial> resultList = iBamuReconciliationSettlementOrderMaterialService.lambdaQuery()
                    .in(BamuReconciliationSettlementOrderMaterial::getReconciliationSettlementId, idList)
                    .list();
            if(CollectionUtils.isNotEmpty(resultList)){
                BigDecimal sum = resultList.stream().map(BamuReconciliationSettlementOrderMaterial::getReconciliationPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                vo.setHistorySettlementAmount(sum);
            }
        }

        // 返回转换后的视图对象
        return vo;
    }

    @Override
    public List<SettlementExcelDto> export(ProjectSettlementDto projectSettlementDto) {
        // 构建查询条件
        LambdaQueryWrapper<BamuReconciliationSettlement> queryWrapper =
                new LambdaQueryWrapper<BamuReconciliationSettlement>()
                        .eq(BamuReconciliationSettlement::getIsDeleted, DataDeletedStatus.NO.getType())
                        .eq(StringUtils.isNotBlank(projectSettlementDto.getContractMethod()),
                                BamuReconciliationSettlement::getContractMethod,
                                projectSettlementDto.getContractMethod())
                        .eq(StringUtils.isNotBlank(projectSettlementDto.getContractId()), BamuReconciliationSettlement::getContractId, projectSettlementDto.getContractId())
                        .eq(StringUtils.isNotBlank(projectSettlementDto.getProjectId()),
                                BamuReconciliationSettlement::getProjectId,
                                projectSettlementDto.getProjectId())
                        .between(StringUtils.isNotBlank(projectSettlementDto.getSettlementStartDate()) && StringUtils.isNotBlank(projectSettlementDto.getSettlementEndDate()),
                                BamuReconciliationSettlement::getSettlementDate,
                                ConvertUtil.getStartOfDay(ConvertUtil.getString2Date(projectSettlementDto.getSettlementStartDate())),
                                ConvertUtil.getEndOfDay(ConvertUtil.getString2Date(projectSettlementDto.getSettlementEndDate())))
                        .like(StringUtils.isNotBlank(projectSettlementDto.getContractNo()),
                                BamuReconciliationSettlement::getContractNo,
                                projectSettlementDto.getContractNo())
                        .like(StringUtils.isNotBlank(projectSettlementDto.getContractName()), BamuReconciliationSettlement::getContractName, projectSettlementDto.getContractName())
                        .like(StringUtils.isNotBlank(projectSettlementDto.getProjectName()), BamuReconciliationSettlement::getProjectName, projectSettlementDto.getProjectName())
                        .like(StringUtils.isNotBlank(projectSettlementDto.getSupplierDeptName()), BamuReconciliationSettlement::getSupplierDeptName, projectSettlementDto.getSupplierDeptName())
                        .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuReconciliationSettlement::getProjectId, BaseContext.getProjectList())
                        .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()),
                                BamuReconciliationSettlement::getSupplierDeptId,
                                BaseContext.getSupplierList()).orderByDesc(BamuReconciliationSettlement::getId)
                        .orderByDesc(BamuReconciliationSettlement::getCreatedAt);
        List<BamuReconciliationSettlement> contractMaterialList = iBamuReconciliationSettlementService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(contractMaterialList)) {
            return contractMaterialList.stream().map(this::convertToExcelDto).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 将BamuContractMaterial转化成ContractMaterialExportDto
     */
    private SettlementExcelDto convertToExcelDto(BamuReconciliationSettlement bamuPurchaseApply) {
        SettlementExcelDto dto = new SettlementExcelDto();
        BeanUtils.copyProperties(bamuPurchaseApply, dto);
        dto.setId(bamuPurchaseApply.getId());
        return dto;
    }


}
